package com.vanzo.ui;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.vanzo.Configure;
import com.vanzo.Tpplication;
import com.vanzo.adapter.TalkieFollowerAdapter;
import com.vanzo.bean.Follower;
import com.vanzo.encryption.R;
import com.vanzo.instruction.AT;
import com.vanzo.service.PttKeyReceiver;

import java.util.List;

/**
 * Created by tisen on 2018/3/8.
 */

public class TalkieFragment2 extends BaseFragment2 implements View.OnTouchListener, CompoundButton.OnCheckedChangeListener, TalkieFollowerAdapter.FollowerClickListener {

    private Button putDownTalkie;
    private Switch talkieSwitch;
    private RecyclerView recycler;
    private TalkieFollowerAdapter talkieFollowerAdapter;
    private List<Follower> followers;
    private ImageView initFollower;
    private TextView followerCountText;
    private View talkieFollowerTitle;
    private ImageView talkieFollowerTitleImage;

    @Override
    protected int getFragmentLayoutId() {
        return R.layout.fragment_talkie2;
    }

    @Override
    protected void initView() {
        putDownTalkie = (Button) getRoot().findViewById(R.id.talkie_button);
        talkieSwitch = (Switch) getRoot().findViewById(R.id.talkie_control);
        recycler = (RecyclerView) getRoot().findViewById(R.id.talkie_followers_recycle);
        initFollower = (ImageView) getRoot().findViewById(R.id.iv_right);
        ((TextView) getRoot().findViewById(R.id.tv_title)).setText("对讲");
        if (tpplication.getMaster().getIsMaster()) {
            initFollower.setVisibility(View.VISIBLE);
        }
        followerCountText = (TextView) getRoot().findViewById(R.id.tv_member_list_title);
        talkieFollowerTitle = getRoot().findViewById(R.id.talkie_followers_title);
        talkieFollowerTitleImage = (ImageView) getRoot().findViewById(R.id.iv_keyboard_down_up);
//        talkieSwitch.setEnabled(false);
    }

    private boolean isFollowerHide = false;

    @Override
    protected void initListener() {
        putDownTalkie.setOnTouchListener(this);
        talkieSwitch.setOnCheckedChangeListener(this);
        initFollower.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow();
            }
        });
        talkieFollowerTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isFollowerHide) {
                    recycler.setVisibility(View.INVISIBLE);
                    talkieFollowerTitleImage.setImageResource(R.mipmap.ic_keyboard_arrow_up_white_24dp);
                } else {
                    recycler.setVisibility(View.VISIBLE);
                    talkieFollowerTitleImage.setImageResource(R.mipmap.ic_keyboard_arrow_down_white_24dp);
                }
                isFollowerHide = !isFollowerHide;
            }
        });
    }

    @Override
    protected void initData() {
//        instruction.start();
        talkieFollowerAdapter = new TalkieFollowerAdapter(getActivity());
        recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        recycler.setAdapter(talkieFollowerAdapter);
        talkieFollowerAdapter.setListener(this);
        followers = tpplication.getFollowers();
        followerCountText.setText("成员列表（" + followers.size() + "）");
        talkieFollowerAdapter.setFollowers(followers);
    }

    private void showPopupWindow() {
        // 用于PopupWindow的View
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_add_mumber, null, false);
        final PopupWindow window = new PopupWindow(contentView, ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.WRAP_CONTENT, true);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.setOutsideTouchable(false);
        window.setFocusable(true);
        window.showAtLocation(getView(), Gravity.CENTER, 0, 0);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        final EditText mGroupNumber = (EditText) contentView.findViewById(R.id.ed_group_number);
        final EditText mMembersGroup = (EditText) contentView.findViewById(R.id.ed_members_group);
        final EditText mStartNumber = (EditText) contentView.findViewById(R.id.ed_start_number);
        final EditText mChannel = (EditText) contentView.findViewById(R.id.ed_channel);
        TextView mEnsure = (TextView) contentView.findViewById(R.id.button_ensure);
        TextView mCancel = (TextView) contentView.findViewById(R.id.button_cancel);

        mEnsure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.dismiss();

                String groupNmmber = mGroupNumber.getText().toString().trim();
                String startNumber = mStartNumber.getText().toString().trim();
                String membersGroup = mMembersGroup.getText().toString().trim();
                String channelNumber = mChannel.getText().toString().trim();

                if (!startNumber.equals("") && !membersGroup.equals("")) {
                    int intStartNumber = Integer.valueOf(startNumber);
                    int intMember = Integer.valueOf(membersGroup);
                    int intGroupNumber = Integer.valueOf(groupNmmber);
                    int intChannel = Integer.valueOf(channelNumber);
                    tpplication.initMasterFollowers(intGroupNumber, intMember, intStartNumber, intChannel);
                    followers = tpplication.getFollowers();
                    followerCountText.setText("成员列表（" + followers.size() + "）");
                    talkieFollowerAdapter.setFollowers(followers);
                }
            }
        });

        mCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.dismiss();
            }
        });
    }

    private boolean isPttTimeOut = false;
    public static final int PTT_TIME_OUT = 100;
    private Handler pttTimeOutHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            isPttTimeOut = true;
            instruction.sendInstruction(AT.DMO_PTT + "=0");
            Toast.makeText(getActivity(), "超过60s,请松手后重新对讲", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.talkie_button) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                instruction.sendInstruction(AT.DMO_PTT + "=1");
                pttTimeOutHandler.sendEmptyMessageDelayed(PTT_TIME_OUT, Configure.PTT_TIME_OUT);
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (isPttTimeOut) {
                    isPttTimeOut = false;
                } else {
                    instruction.sendInstruction(AT.DMO_PTT + "=0");
                    pttTimeOutHandler.removeMessages(PTT_TIME_OUT);
                }
            }
            return false;
        }
        return false;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView.getId() == R.id.talkie_control) {
            if (isChecked) {
                instruction.connect();
                Tpplication.Channel channel = tpplication.getChannels().get(tpplication.getMaster().getChannelId());
                instruction.switchChannel(channel.getChannel(), channel.getTfreq(), channel.getRfreq());
            } else {
                instruction.disconnect();
            }
        }
    }

    public void refreshFollower() {
        followers = tpplication.getFollowers();
        followerCountText.setText("成员列表（" + followers.size() + "）");
        talkieFollowerAdapter.setFollowers(followers);
    }

    @Override
    public void onNFCBindClick(int position) {
        bindNFC.onBindNFC(position);
    }

    @Override
    public void onMessageClick(int position) {
        Toast.makeText(getActivity(), "onMessageClick position = " + position, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onVoiceClick(int position) {
        Toast.makeText(getActivity(), "onVoiceClick position = " + position, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDeleteClick(int position) {
        Follower follower = tpplication.getFollowers().get(position);
        follower.switchKillState();
        tpplication.updateFollower(follower);
        talkieFollowerAdapter.setFollowers(tpplication.getFollowers());
    }

    private BindNFC bindNFC;

    public void setBindNFC(BindNFC bindNFC) {
        this.bindNFC = bindNFC;
    }

    public void setAction(String action) {
        if (action.equals(PttKeyReceiver.ACTION_PTT_DOWN)) {
            putDownTalkie.setPressed(true);
        } else if (action.equals(PttKeyReceiver.ACTION_PTT_UP)) {
            putDownTalkie.setPressed(false);
        }
    }

    public interface BindNFC {
        void onBindNFC(int position);
    }
}
